package workforce.limousine.struts;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;
import limousine.util.Func;
import limousine.util.Service;
import limousine.util.Token;
import limousine.vo.UserContext;
import limousine.vo.UserControl;
import limousine.vo.Users;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;


public class Signin extends Action {

    private Func func = new Func();
    
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        System.out.println("***Signin");

        HttpSession session = request.getSession();

        //Users user = (Users)session.getAttribute(Token.USER_SESSION);
		/*if(user == null){
        System.out.println("--SESSION EXPIRE--");
        return mapping.findForward(Token.SESSION_EXPIRE);
        }
        if(!user.getUser_name().equals("admin")){
        System.out.println("--Not admin Hack--");
        return mapping.findForward(Token.SESSION_EXPIRE);
        }*/

        session.removeAttribute(Token.USER_SESSION);
        session.removeAttribute(Token.USER_CONTROL);

       

//        DataSource ds = this.getDataSource(request, Token.DATASOURCE_NAME);
        Service service = new Service();
        service.setServletContext(this.getServlet().getServletContext());
        DataSource ds = service.getDataSource();
        
        
        service.removeMsgAttribute(request, session, "");


        DynaActionForm f = (DynaActionForm) form;
        String userName = f.getString("userName");
        userName = checkEmptyString(userName);
        if (userName.length() == 0) {
            session.setAttribute(Token.MSG_ERROR, "Not have userName");
            return mapping.findForward(Token.FAIL);
        }

        String password = f.getString("password");
        password = checkEmptyString(password);
        if (password.length() == 0) {
            session.setAttribute(Token.MSG_ERROR, "Not have password");
            return mapping.findForward(Token.FAIL);
        }

        String callbackUrl = f.getString("callbackUrl");

        System.out.println("User:["+userName+"] pass:["+password+"]");
        Users user_systems = service.signinCheck(ds, userName, password);
       
        
        if (user_systems != null) {
            service.updateLastLogin(ds, user_systems.getId());//update last login

            session.setAttribute(Token.USER_SESSION, user_systems);
            keepAllLoginToContext(session,user_systems);

            List<UserControl> list = new ArrayList<UserControl>();
            list = service.getUserControl(ds, user_systems.getRoleId());
            System.out.println("Size " + list.size());
            if (list.size() > 0) {
                session.setAttribute(Token.USER_CONTROL, list);
            }
            System.out.println(">>Signin success [" + userName + "]");
            
            
            if(callbackUrl != null && callbackUrl.length()>0){
                ActionForward af = new ActionForward(callbackUrl, true);
                return af;
            }else{
                /*if(Integer.parseInt(user_systems.getRoleId()) > Config.ROLE_USER){
                    ActionForward af = new ActionForward("/home.jsp", true);
                    return af;
                }*/

                return mapping.findForward(Token.SUCCESS);
            }
        } else {
            System.out.println(">>Signin fail [" + userName + "]");
            session.setAttribute(Token.MSG_ERROR, "กรุณาตรวจสอบ<br>การป้อนข้อมูลฺใหม่ค่ะ");

            if(callbackUrl != null && callbackUrl.length()>0){
                ActionForward af = new ActionForward(callbackUrl+"?msg=fail", true);
                return af;
            }else{
//                ActionForward af = new ActionForward(callbackUrl+"?msg=fail", true);
//                return af;
                return mapping.findForward(Token.FAIL);
            }
        }
    }
    private String checkEmptyString(String value) {// optimize data
        value = (value == null) ? "" : value.trim();
        return func.jsp2UTF(value);
    }
    private void keepAllLoginToContext(HttpSession session,Users user){
		 session.setAttribute(Token.USER_SESSION, user);
                 
//		keep all login to context
		UserContext uscontext = new UserContext();
		uscontext.setUserID(user.getId());
		uscontext.setLoginTime(func.longDateToString(func.getLongDate()));
		List<UserContext> userContextList = (ArrayList<UserContext>)this.getServlet().getServletContext().getAttribute(Token.USER_CONTEXT_LIST);
		if(userContextList == null){
			userContextList = new ArrayList<UserContext>();
		}
		userContextList.add(uscontext);
		this.getServlet().getServletContext().setAttribute(Token.USER_CONTEXT_LIST,userContextList);
		//keep all login to context
	}
}
